package com.zygk.locationtool.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.zygk.library.base.BaseActivity;
import com.zygk.library.util.ToastUtil;
import com.zygk.locationtool.R;
import com.zygk.locationtool.config.Constants;
import com.zygk.locationtool.config.Urls;
import com.zygk.locationtool.dao.StationLogic;
import com.zygk.locationtool.model.M_Station;
import com.zygk.locationtool.util.HttpRequest;
import com.zygk.locationtool.util.RxLocationTool;
import com.zygk.locationtool.view.MyWebView;
import java.util.Iterator;
import org.json.JSONException;
import org.json.JSONObject;
import wendu.dsbridge.CompletionHandler;
import wendu.dsbridge.OnReturnValue;

public class MapActivity extends BaseActivity implements LocationListener {
  public static final String INTENT_STATION = "INTENT_STATION";

  @BindView(R.id.layout_head) RelativeLayout layoutHead;
  @BindView(R.id.webView) MyWebView webView;
  @BindView(R.id.tv_right) TextView tvRight;
  @BindView(R.id.ll_right) LinearLayout llRight;
  @BindView(R.id.lh_tv_title) TextView lhTvTitle;

  private Context mContext;
  private Activity mActivity;
  private CompletionHandler mHandler;
  private LocationManager locationManager;
  private Location mLocation;
  private M_Station mStation;

  MaterialDialog.Builder builder = new MaterialDialog.Builder(mContext);
  MaterialDialog materialDialog;

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ButterKnife.bind(this);
  }

  @Override public void setContentView() {
    setContentView(R.layout.activity_main);
  }

  @Override public void init() {
    initData();
    initView();
    getLocation();
  }

  private void initData() {
    mContext = this;
    mActivity = this;
    mStation = (M_Station) getIntent().getSerializableExtra(INTENT_STATION);
    if (null == mStation) mStation = new M_Station();
    initLocation();
    gpsCheck();
  }

  private void initView() {
    lhTvTitle.setText(mStation.getStationName());
    llRight.setVisibility(View.VISIBLE);
    tvRight.setText("保存");
  }

  private void initWebView() {
    webView.clearCache(true);
    webView.addJavascriptObject(new JsApi(), null);
    webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    webView.loadUrl(Urls.MAP_URL);
    webView.setWebChromeClient(new WebChromeClient());
    webView.setWebViewClient(new MyWebViewClient());
  }

  class MyWebViewClient extends WebViewClient {
    @Override public void onPageFinished(WebView view, String url) {
      super.onPageFinished(view, url);
      if (mLocation != null) {
        if (mStation.isHasSet()) {
          String stationLonLat = mStation.getLocation();
          String[] lonLat = stationLonLat.split(",");
          webView.callHandler("editLoc", new Object[] {
              mLocation.getLongitude(), mLocation.getLatitude(), lonLat[0], lonLat[1]
          }, new OnReturnValue() {
            @Override public void onValue(Object jsonObject) {

            }
          });
        } else {
          webView.callHandler("addLoc",
              new Object[] { mLocation.getLongitude(), mLocation.getLatitude() },
              new OnReturnValue() {
                @Override public void onValue(Object jsonObject) {
                  try {
                    JSONObject j = new JSONObject(jsonObject.toString());
                    JSONObject jBaidu = j.getJSONObject("baidu");
                    JSONObject jGaode = j.getJSONObject("gaode");
                    JSONObject jGps = j.getJSONObject("wgs84");
                    mStation.setLocation_AMap(
                        jGaode.getString("lng") + "," + jGaode.getString("lat"));
                    mStation.setLocation_BMap(
                        jBaidu.getString("lng") + "," + jBaidu.getString("lat"));
                    mStation.setLocation(jGps.getString("lng") + "," + jGps.getString("lat"));
                  } catch (JSONException e) {
                    e.printStackTrace();
                  }
                }
              });
        }
      }
    }
  }

  class JsApi {

    Intent intent;

    @JavascriptInterface public void saveLoc(Object jsonObject, CompletionHandler handler) {
      mHandler = handler;
      //System.out.println(jsonObject.toString());
      try {
        JSONObject j = new JSONObject(jsonObject.toString());
        JSONObject jBaidu = j.getJSONObject("baidu");
        JSONObject jGaode = j.getJSONObject("gaode");
        JSONObject jGps = j.getJSONObject("wgs84");
        mStation.setLocation_AMap(jGaode.getString("lng") + "," + jGaode.getString("lat"));
        mStation.setLocation_BMap(jBaidu.getString("lng") + "," + jBaidu.getString("lat"));
        mStation.setLocation(jGps.getString("lng") + "," + jGps.getString("lat"));
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
  }

  private void initLocation() {
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
  }

  private void gpsCheck() {
    if (!RxLocationTool.isGpsEnabled(mContext)) {
      materialDialog = builder.title("GPS未打开")
          .content("您需要在系统设置中打开GPS方可采集数据")
          .positiveText("去设置")
          .onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
              RxLocationTool.openGpsSettings(mContext);
              dialog.dismiss();
            }
          })
          .build();
      materialDialog.setCanceledOnTouchOutside(false);
      materialDialog.setCancelable(false);
      materialDialog.show();
    } else {
      getLocation();
    }
  }

  private void getLocation() {
    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION)
        != PackageManager.PERMISSION_GRANTED
        && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION)
        != PackageManager.PERMISSION_GRANTED) {
      ActivityCompat.requestPermissions(mActivity, new String[] {
          Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
      }, 1);
      return;
    }

    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 0, this);
    locationManager.addGpsStatusListener(new GpsStatus.Listener() {
      @Override public void onGpsStatusChanged(int event) {
        switch (event) {
          case GpsStatus.GPS_EVENT_STARTED:
            //System.out.println("GPS_EVENT_STARTED");
            break;
          case GpsStatus.GPS_EVENT_FIRST_FIX:
            //System.out.println("GPS_EVENT_FIRST_FIX");
            break;
          case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
            //System.out.println("GPS_EVENT_SATELLITE_STATUS");
            if (ActivityCompat.checkSelfPermission(mContext,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
              return;
            }
            GpsStatus gpsStatus = locationManager.getGpsStatus(null);
            Iterable<GpsSatellite> gpsSatellites = gpsStatus.getSatellites();
            int count = 0;
            Iterator iterator = gpsSatellites.iterator();
            while (iterator.hasNext()) {
              count++;
              iterator.next();
            }
            break;
          case GpsStatus.GPS_EVENT_STOPPED:
            System.out.println("GPS_EVENT_STOPPED");
            //gpsState.setText("已停止定位");
            break;
        }
      }
    });
  }

  @Override public void onLocationChanged(Location location) {
    if (location != null) {
      mLocation = location;
      initWebView();
      locationManager.removeUpdates(this);
    }
  }

  @Override public void onStatusChanged(String provider, int status, Bundle extras) {

  }

  @Override public void onProviderEnabled(String provider) {

  }

  @Override public void onProviderDisabled(String provider) {

  }

  private void saveStationLocation() {
    StationLogic.saveStationLocation(mContext, mStation, new HttpRequest.HttpCallback() {
      @Override public void onStart() {
        showPd();
      }

      @Override public void onSucceed(Object obj) {
        ToastUtil.showMessage(mContext, "保存成功");
        sendBroadcast(new Intent(Constants.BROADCAST_REFRESH_STATION_LIST));
        finish();
      }

      @Override public void onFailed() {

      }

      @Override public void onFinish() {
        dismissPd();
      }
    });
  }

  @OnClick({ R.id.ll_back, R.id.ll_right }) public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.ll_back:
        finish();
        break;
      case R.id.ll_right:
        saveStationLocation();
        break;
    }
  }
}
